﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using NHibernate;
using Spring.Data.NHibernate.Generic;
using Spring.Data.NHibernate.Generic.Support;
using Hospital.Common;
using Hospital.Model;
using Hospital.Dao;
using Hospital.Dao.IDao;

namespace Hospital.Dao.DaoImpl
{
    public class UserDaoImpl : HibernateDaoSupport, IUserDao
    {

        private SQLHelper sqlHelper;

        public SQLHelper SqlHelper
        {
            set { sqlHelper = value; }
            get { return sqlHelper; }
        }

        #region IUserDao 成员

        public IList<User> GetAllUsers()
        {
            return HibernateTemplate.LoadAll<User>();
        }

        public User GetUserById(int Id)
        {
            return (User)HibernateTemplate.Execute(new HibernateDelegate<User>(delegate(NHibernate.ISession session)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("from User c  where c.Id=?");
                IQuery query = session.CreateQuery(sb.ToString());
                query.SetParameter(0, Id);
                return query.UniqueResult() as User;
            }), true);
        }

        public bool AddUser(User user)
        {
            if (HibernateTemplate.Save(user) != null)
            {
                return true;
            }
            return false;
        }

        public bool UpdateUser(User user)
        {
            HibernateTemplate.Update(user);
            return true;
        }

        public bool AddOrUpdateUser(User user)
        {
            HibernateTemplate.SaveOrUpdate(user);
            return true;
        }

        public bool DeleteUser(User user)
        {
            HibernateTemplate.Delete(user);
            return true;
        }

        public DataTable GetAllUser()
        {
            return sqlHelper.ExecuteDataTable(" select * from t_User ", false, null);
        }

        public User GetUserByName(string strUserName)
        {
            return (User)HibernateTemplate.Execute(new HibernateDelegate<User>(delegate(NHibernate.ISession session)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("from User c  where c.UserName=?");
                IQuery query = session.CreateQuery(sb.ToString());
                query.SetParameter(0, strUserName);
                return query.UniqueResult() as User;
            }), true);
        }

        #endregion
    }
}
